<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>C# data types</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, data types, tutorial, programming language, .NET, Mono">
<meta name="description" content="This part of the C# tutorial covers data types.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>



<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>C# data types</h1>

<p>
In this part of the C# tutorial, we will talk about data types. 
</p>

<p>
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients.
Tools to work with various data types are essential part of a modern computer language. 
A <b class="keyword">data type</b> is a set of values, and the allowable operations on 
those values.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
The two fundamental data types in C# are value types and reference types.
Primitive types (except strings), enumerations, and structures are value types.
Classes, strings, interfaces, arrays, and delegates are reference types.
Every type has a default value.
<b>Reference types</b> are created on the Heap. The lifetime of the reference type is
managed by the .NET framework. The default value for reference types is null
reference. Assignment to a variable of a reference type creates a copy of the reference rather
than a copy of the referenced value.
<b>Value types</b> are created on the stack. The lifetime is determined by the
lifetime of the variable. Assignment to a variable of a value type creates a copy of the
value being assigned. Value types have different default values. For example, boolean
default value is false, decimal 0, string an empty string "".
</p>



<h2>Boolean values</h2>

<p>
There is a duality built in our world. There is a Heaven and Earth, water and fire, 
jing and jang, man and woman, love and hatred. In C# the 
<b class="keyword">bool</b> data type is a primitive data type having one 
of two values: <b class="keyword">true</b> or <b class="keyword">false</b>. 
This is a fundamental data type. Very common in computer programs.
</p>

<p>
Happy parents are waiting a child to be born. They have chosen a name for both
possibilities. If it is going to be a boy, they have chosen John. If it is
going to be a girl, they have chosen Victoria. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        bool male = false;

        Random random = new Random();
        male = Convert.ToBoolean(random.Next(0, 2));

        if (male) {
            Console.WriteLine("We will use name John");
        } else {
            Console.WriteLine("We will use name Victoria");
        }
    }
}
</pre>

<p>
The program uses a random number generator to simulate our case. 
</p>

<pre class="explanation">
bool male = false;
</pre>

<p>
The male variable is our boolean variable, initiated at first to
false. 
</p>

<pre class="explanation">
Random random = new Random();
</pre>

<p>
We create a <b class="keyword">Random</b> object, which is used to compute random numbers.
It is part of the System namespace.
</p>

<pre class="explanation">
male = Convert.ToBoolean(random.Next(0, 2));
</pre>

<p>
The <code>Next()</code> method returns a random number within a specified 
range. The lower bound is included, the upper bound is not.
In other words, we receive either 0, or 1. Later the <code>Convert()</code>
method converts these values to boolean ones. 0 to false,
1 to true.
</p>


<pre class="explanation">
if (male) {
    Console.WriteLine("We will use name John");
} else {
    Console.WriteLine("We will use name Victoria");
}
</pre>

<p>
If the male variable is set to true, we choose name John.
Otherwise, we choose name Victoria. Control structures like
if/else statements work with boolean values. 
</p>

<pre>
$ ./kid.exe 
We will use name Victoria
$ ./kid.exe 
We will use name John
$ ./kid.exe 
We will use name John
</pre>

<p>
Running the program several times. 
</p>



<h2>Integers</h2>

<p>
Integers are a subset of the real numbers. They are written without 
a fraction or a decimal component. Integers fall within a set
Z = {..., -2, -1, 0, 1, 2, ...} Integers are infinite. 
</p>

<p>
In computer languages, integers are primitive data types. Computers can 
practically work only with a subset of integer values, because computers
have finite capacity. Integers are used to count discrete entities. We 
can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can 
have 3.33 kilograms.
</p>

<table>
<tbody>
<tr>
<th>VB Alias</th>
<th>.NET Type</th>
<th>Size</th>
<th>Range</th>
</tr>
<tr>
<td>sbyte</td>
<td>System.SByte</td>
<td>1 byte</td>

<td>-128 to 127</td>
</tr>
<tr class="gray">
<td>byte</td>
<td>System.Byte</td>
<td>1 byte</td>
<td>0 to 255</td>
</tr>
<tr>
<td>short</td>
<td>System.Int16</td>

<td>2 bytes</td>
<td>-32,768 to 32,767</td>
</tr>
<tr class="gray">
<td>ushort</td>
<td>System.UInt16</td>
<td>2 bytes</td>
<td>0 to 65,535</td>
</tr>
<tr>
<td>int</td>
<td>System.Int32</td>
<td>4 bytes</td>
<td>-2,147,483,648 to 2,147,483,647</td>
</tr>
<tr class="gray">
<td>uint</td>
<td>System.UInt32</td>
<td>4 bytes</td>
<td>0 to 4,294,967,295</td>
</tr>
<tr>
<td>long</td>
<td>System.Int64</td>
<td>8 bytes</td>
<td>-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807</td>
</tr>
<tr class="gray">
<td>ulong</td>
<td>System.UInt64</td>
<td>8 bytes</td>

<td>0 to 18,446,744,073,709,551,615</td>
</tr>
</tbody>
</table>

<p>
These integer types may be used according to our needs. No one, 
(except perhaps for some biblical people), can be older than 120, 130
years. We can then use the <code>byte</code> type for age variable in
a program. This will save some memory. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {        
        byte a = 254;
        
        Console.WriteLine(a);
        a++;
        Console.WriteLine(a);
        a++;
        Console.WriteLine(a);
        a++;
        Console.WriteLine(a);
    }
}
</pre>

<p>
In this example, we try to assign a value beyond the range
of a data type. This leads to an arithmetic overflow. 
An <b>arithmetic overflow</b> is a condition that occurs when a 
calculation produces a result that is greater in magnitude than 
that which a given register or storage location can store or 
represent. 
</p>

<pre>
$ ./overflow.exe 
254
255
0
1
</pre>

<p>
In C#, when an overflow occurs, the variable is reset to zero.
In contrast, Visual Basic would throw an exception.
</p>

<hr class="btm">

<p>
<b>Notations</b> Integers can be specified in two different <b>notations</b> in 
C#. Decimal and hexadecimal. There are no notations for octal
or binary values. Decimal numbers are used normally, as we know
them. Hexadecimal numbers are preceded with 0x characters.
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {        
        int num1 = 31;
        int num2 = 0x31;
        
        Console.WriteLine(num1);
        Console.WriteLine(num2);
    }
}
</pre>

<p>
We assign 31 to two variables using two different notations. 
And we print them to the console.
</p>

<pre>
$ ./intnotations.exe 
31
49
</pre>

<p>
The default notation is the decimal. The program shows these 
two numbers in decimal. In other words, hexadecimal 0x31 is
49 decimal.
</p>

<hr class="btm">

<p>
<b>Counting apples</b> If we work with integers, we deal with discrete 
entities. We would use integers to count apples. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {

        // number of baskets
        int baskets = 16;

        // number of apples in each basket 
        int apples_in_basket = 24;

        // total number of apples
        int total = baskets * apples_in_basket;

        Console.WriteLine("There are total of {0} apples", total);
        
    }
}
</pre>


<p>
In our program, we count the total amount of apples. We use the 
multiplication operation. 
</p>

<pre>
$ ./apples.exe 
There are total of 384 apples

</pre>

<p>
The output of the program. 
</p>

<h2>Floating point numbers</h2>

<p>
Floating point numbers represent real numbers in computing. Real numbers 
measure continuous quantities. Like weight, height or speed. In C# we have 
three floating point types: float, double and decimal.
</p>

<table>
<tbody>
<tr>
<th>C# Alias</th>
<th>.NET Type</th>
<th>Size</th>
<th>Precision</th>
<th>Range</th>
</tr>
<tr>
<td>float</td>
<td>System.Single</td>

<td>4 bytes</td>
<td>7 digits</td>
<td>1.5 x 10<sup>-45</sup> to 3.4 x 10<sup>38</sup></td>
</tr>
<tr class="gray">
<td>double</td>
<td>System.Double</td>
<td>8 bytes</td>

<td>15-16 digits</td>
<td>5.0 x 10<sup>-324</sup> to 1.7 x 10<sup>308</sup></td>
</tr>
<tr>
<td>decimal</td>
<td>System.Decimal</td>
<td>16 bytes</td>
<td>28-29 decimal places</td>

<td>1.0 x 10<sup>-28</sup> to 7.9 x 10<sup>28</sup></td>
</tr>
</tbody>
</table>

<p>
The above table gives the characteristics of the floating point types. 
</p>


<p>
By default, real numbers are double in C# programs. To use a different
type, we must use a suffix. The F/f for <code>float</code> numbers and M/m for 
<code>decimal</code> numbers.
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        float   n1 = 1.234f;
        double  n2 = 1.234;
        decimal n3 = 1.234m;

        Console.WriteLine(n1);
        Console.WriteLine(n2);
        Console.WriteLine(n3);

        Console.WriteLine(n1.GetType());
        Console.WriteLine(n2.GetType());
        Console.WriteLine(n3.GetType());
    }
}
</pre>

<p>
In the above program, we use three different literal notations
for floating point numbers. 
</p>

<pre class="explanation">
float   n1 = 1.234f;
</pre>

<p>
The f suffix is used for a <code>float</code> number.
</p>

<pre class="explanation">
double  n2 = 1.234;
</pre>

<p>
If we don't use a suffix, then it is a <code>double</code> number.
</p>

<pre class="explanation">
Console.WriteLine(n1.GetType());
</pre>

<p>
The <code>GetType()</code> method returns the type of the number.
</p>

<pre>
$ ./floats.exe
1.234
1.234
1.234
System.Single
System.Double
System.Decimal
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
We can use various syntax to create floating point values.
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        float n1 = 1.234f;
        float n2 = 1.2e-3f;
        float n3 = (float) 1 / 3;

        Console.WriteLine(n1);
        Console.WriteLine(n2);
        Console.WriteLine(n3);
    }
}
</pre>

<p>
We have three ways to create floating point values. The first 
is the 'normal' way using a decimal point. The second uses 
scientific notation. And the last one as a result of a 
numerical operation. 
</p>

<pre class="explanation">
float n2 = 1.2e-3f;
</pre>

<p>
This is the scientific notation for floating point numbers.
Also known as exponential notation, it is a way of writing numbers
too large or small to be conveniently written in standard decimal 
notation.
</p>

<pre class="explanation">
float n3 = (float) 1 / 3;
</pre>

<p>
The <code>(float)</code> construct is called casting. The division
operation returns integer numbers by default. By casting we get
a float number. 
</p>

<pre>
$ ./fnotations.exe 
1.234
0.0012
0.3333333
</pre>

<p>
This is the output of the above program. 
</p>

<hr class="btm">

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        float  n1 = (float) 1 / 3;
        double n2 = (double) 1 / 3;

        if (n1 == n2) 
        {
            Console.WriteLine("Numbers are equal");
        } else {
            Console.WriteLine("Numbers are not equal");
        }
    }
}
</pre>

<p>
The <code>float</code> and <code>double</code> values are stored 
with different precision. Caution should be exercised when comparing 
floating point values. 
</p>

<pre>
$ ./fequal.exe 
Numbers are not equal
</pre>

<p>
And the numbers are not equal. 
</p>

<hr class="btm">

<p>
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        float distance;
        float time;
        float speed;
        
        // 100m is 0.1 km

        distance = 0.1f;

        // 9.87s is 9.87/60*60 h

        time = 9.87f / 3600;

        speed = distance / time;

        Console.WriteLine("The average speed of a sprinter is {0} km/h", speed);
    }
}
</pre>

<p>
In this example, it is necessary to use floating point values. 
</p>

<pre class="explanation">
speed = distance / time;
</pre>

<p>
To get the speed, we divide the distance by the time. 
</p>


<pre>
$ ./sprinter.exe 
The average speed of a sprinter is 36.47416 km/h
</pre>

<p>
This is the output of the sprinter program. 
</p>

<h2>Enumerations</h2>

<p>
Enumerated type (also called enumeration or enum) 
is a data type consisting of a set of named values.
A variable that has been declared as having an enumerated type can 
be assigned any of the enumerators as a value. Enumerations make
the code more readable. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    enum Days 
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }

    static void Main()
    {

        Days day = Days.Monday;
        
        if (day == Days.Monday)
        {
            Console.WriteLine("It is Monday");
        }

        Console.WriteLine(day);

        foreach(int i in Enum.GetValues(typeof(Days)))
            Console.WriteLine(i);
    }
}
</pre>

<p>
In our code example, we create an enumeration for week days. 
</p>

<pre class="code">
enum Days 
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
</pre>

<p>
The enumeration is created with a <code>enum</code> keyword.
The Monday, Tuesday ... barewords store in fact numbers 0..6. 
</p>

<pre class="explanation">
Days day = Days.Monday;
</pre>

<p>
We have a variable called day, which is of enumerated type Days.
It is initialized to Monday.
</p>

<pre class="explanation">
if (day == Days.Monday)
{
    Console.WriteLine("It is Monday");
}
</pre>

<p>
This code is more readable than if comparing
a day variable to some number. 
</p>


<pre class="explanation">
Console.WriteLine(day);
</pre>

<p>
This line prints Monday to the console. 
</p>

<pre class="explanation">
foreach(int i in Enum.GetValues(typeof(Days)))
    Console.WriteLine(i);
</pre>

<p>
This loop prints 0..6 to the console. We get underlying
types of the enum values. For a computer, an enum is 
just a number. The <code>typeof</code> is an operator 
used to obtain the System.Type object for a type. It is needed
by the <code>GetValues()</code> method. This method returns an
array of the values of in a specified enumeration. And the 
<code>foreach</code> keyword goes through the array, element
by element and prints them to the terminal.
</p>

<hr class="btm">

<p>
We further work with enumerations. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    public enum Seasons : byte
    {
        Spring = 1,
        Summer = 2,
        Autumn = 3,
        Winter = 4
    }

    static void Main()
    {
        Seasons s1 = Seasons.Spring;
        Seasons s2 = Seasons.Autumn;
        
        Console.WriteLine(s1);
        Console.WriteLine(s2);
    }
}
</pre>

<p>
Seasons can be easily used as enums. We can specify
the underlying type for the enum plus we can give exact
values for them. 
</p>

<pre class="explanation">
public enum Seasons : byte
{
    Spring = 1,
    Summer = 2,
    Autumn = 3,
    Winter = 4
}
</pre>

<p>
With a colon and a data type we specify the
underlying type for the enum. We also give each member a
specific number. 
</p>

<pre class="explanation">
Console.WriteLine(s1);
Console.WriteLine(s2);
</pre>

<p>
These two lines print the enum values to the console. 
</p>

<pre>
$ ./seasons.exe 
Spring
Autumn
</pre>

<p>
Output. 
</p>


<h2>Strings and chars</h2>

<p>
<b class="keyword">string</b> is a data type representing textual data in computer programs.
A string in C# is a sequence of unicode characters. A <b class="keyword">char</b>
is a single unicode character. Strings are enclosed by double quotes.
</p>

<p>
Since strings are very important in every programming language, we will dedicate a whole 
chapter to them. Here we only drop a small example. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        string word = "ZetCode";

        char c = word[0];

        Console.WriteLine(c);
    }
}
</pre>

<p>
The program prints Z character to the terminal. 
</p>

<pre class="explanation">
string word = "ZetCode";
</pre>

<p>
Here we create a string variable and assign it "ZetCode" value.
</p>

<pre class="explanation">
char c = word[0];
</pre>

<p>
A <code>string</code> is an array of unicode characters. We can
use the array access notation to get a specific character from
the string. The number inside the square brackets is the index
into the array of characters. The index is counted from zero.
That means, the first character has index 0. 
</p>

<pre>
$ ./char.exe 
Z
</pre>

<p>
The program prints the first character of the "ZetCode" string
to the console. 
</p>


<h2>Arrays</h2>

<p>
Array is a complex data type which handles a collection of elements. 
Each of the elements can be accessed by an index. All the elements 
of an array must be of the same data type. 
</p>

<p>
We dedicate a whole chapter to arrays, here we show only a small example. 
</p>


<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        
        int[] numbers = new int[5];

        numbers[0] = 3;
        numbers[1] = 2;
        numbers[2] = 1;
        numbers[3] = 5;
        numbers[4] = 6;

        int len = numbers.Length;

        for (int i=0; i&lt;len; i++) 
        {
            Console.WriteLine(numbers[i]);
        }
    }
}
</pre>

<p>
In this example, we declare an array, fill it with data
and then print the contents of the array to the console. 
</p>

<pre class="explanation">
int[] numbers = new int[5];
</pre>

<p>
We declare an integer array, which can store up to 5
integers. So we have an array of five elements, with 
indexes 0..4. 
</p>

<pre class="explanation">
numbers[0] = 3;
numbers[1] = 2;
numbers[2] = 1;
numbers[3] = 5;
numbers[4] = 6;
</pre>

<p>
Here we assign values to the created array. We can access
the elements of an array by the array access notation. It
consists of the array name followed by square brackets. Inside
the brackets we specify the index to the element, we want.
</p>

<pre class="explanation">
int len = numbers.Length;
</pre>

<p>
Each array has a <code>Length</code> property, which returns
the number of elements in the array.
</p>

<pre class="explanation">
for (int i=0; i&lt;len; i++) 
{
    Console.WriteLine(numbers[i]);
}
</pre>

<p>
We traverse the array and print the data to the
console. 
</p>


<h2>DateTime</h2>

<p>
The <b class="keyword">DateTime</b> is value type. It represents an 
instant in time, typically expressed as a date and time of day.
</p>


<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        DateTime today;

        today = DateTime.Now;

        System.Console.WriteLine(today);
        System.Console.WriteLine(today.ToShortDateString());
        System.Console.WriteLine(today.ToShortTimeString());               

    }
}
</pre>

<p>
We show today's date in three different formats. Date &amp; time, 
date and time. 
</p>

<pre class="explanation">
DateTime today;
</pre>

<p>
We declare a variable of <code>DateTime</code> data type. 
</p>

<pre class="explanation">
today = DateTime.Now;
</pre>

<p>
Gets a DateTime object that is set to the current date and time 
on this computer, expressed as the local time.
</p>

<pre class="explanation">
System.Console.WriteLine(today);
</pre>

<p>
This line prints the date in full format. 
</p>

<pre class="explanation">
System.Console.WriteLine(today.ToShortDateString());
System.Console.WriteLine(today.ToShortTimeString());
</pre>

<p>
The <code>ToShortDateString()</code>
returns a short date string format, the <code>ToShortTimeString()</code>
returns a short time string format. 
</p>

<pre>
$ ./date.exe 
10/15/2010 10:56:37 AM
10/15/2010
10:56 AM
</pre>

<p>
The output of the example.
</p>


<h2>Type casting</h2>

<p>
We often work with multiple data types at once. Converting one data 
type to another one is a common job in programming. <b>Type conversion</b> 
or <b>typecasting</b> refers to changing an entity of one data type 
into another. There are two types of conversion. Implicit and explicit. 
Implicit type conversion, also known as coercion, is an automatic type 
conversion by the compiler. 
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {

        int  val1 = 0;
        byte val2 = 15;

        val1 = val2;         

        Console.WriteLine(val1.GetType());
        Console.WriteLine(val2.GetType());

        Console.WriteLine(12 + 12.5);
        Console.WriteLine("12" + 12);

    }
}
</pre>

<p>
In this example, we have several implicit conversions. 
</p>

<pre class="explanation">
val1 = val2; 
</pre>

<p>
Here we work with two different types. <code>int</code> and 
<code>byte</code>. We assign a <code>byte</code> value to an
<code>int</code> value. It is a widening operation. int values
have four bytes, byte values have only one byte. <b>Widening</b>  
conversions are allowed. If we wanted to assign a <code>int</code>
to a <code>byte</code>, this would be a <b>shortening</b> conversion. 
Implicit shortening conversions are not allowed by C# compiler.
This is because in implicit shortening conversion we could 
unintentionally loose precision. We can do shortening conversions,
but we must inform the compiler about it. That we know what we
are doing. It can be done with explicit conversion. 
</p>

<pre class="explanation">
Console.WriteLine(12 + 12.5);        
</pre>

<p>
We add two values. One integer and one floating point value.
The result is a floating point value. It is a widening
implicit conversion.
</p>

<pre class="explanation">
Console.WriteLine("12" + 12);
</pre>

<p>
The result is 1212. An integer is converted to a string and
the two strings are concatenated. 
</p>

<hr class="btm">>

<p>
Next we will show some explicit conversions in C#.
</p>


<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        float a;
        double b = 13.5;
        int c;
        
        a = (float) b;
        c = (int) a;

        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
    }
}
</pre>

<p>
We have three values. We do some explicit conversions with these
values. 
</p>

<pre class="explanation">
float a;
double b = 13.5;
int c;
</pre>

<p>
We have a <code>float</code> value a <code>double</code> value
and a <code>int</code> value.
</p>

<pre class="explanation">
a = (float) b;
</pre>

<p>
We convert a <code>double</code> value to a <code>float</code>
value. Explicit conversion is done by specifying the intended
type between two square brackets. In this case, no precision
is lost. 13.5 can be safely assigned to both types.
</p>

<pre class="explanation">
c = (int) a;
</pre>

<p>
We convert a <code>float</code> value to <code>int</code> value. 
In this statement, we loose some precision. 13.5 becomes 13.
</p>

<pre>
$ ./explicit.exe 
13.5
13.5
13
</pre>

<p>
Output of the example. 
</p>

<h2>Nullable types</h2>

<p>
Value types cannot be assigned a <code>null</code> literal. Reference types can.
Applications that work with databases deal with the null value. 
Because of this, special nullable types were introduced into the C# language.
Nullable types are instances of the <code>System.Nullable&lt;T&gt;</code> 
struct.
</p>


<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        Nullable&lt;bool&gt; male = null;
        int? age = null;

        Console.WriteLine(male.HasValue);
        Console.WriteLine(age.HasValue);
    }
}
</pre>

<p>
A simple example demonstrating nullable types.
</p>

<pre class="explanation">
Nullable&lt;bool&gt; male = null;
int? age = null;
</pre>

<p>
There are two ways how to declare a nullable type. Either with
the Nullable&lt;T&gt; generic structure, in which the type is specified
between the angle brackets. Or we can use a question mark after
the type. The latter is in fact a shorthand for the first notation.
</p>

<pre>
$ ./nullabletypes.exe 
False
False
</pre>

<p>
Output.
</p>


<h2>Convert &amp; Parse methods</h2>

<p>
There are two groups of methods, which aid us at converting values.
</p>

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(Convert.ToBoolean(0.3));
        Console.WriteLine(Convert.ToBoolean(3));
        Console.WriteLine(Convert.ToBoolean(0));
        Console.WriteLine(Convert.ToBoolean(-1));

        Console.WriteLine(Convert.ToInt32("452"));
        Console.WriteLine(Convert.ToInt32(34.5));
    }
}
</pre>

<p>
The <code>Convert</code> class has many methods for converting values.
We use two of them.
</p>

<pre class="explanation">
Console.WriteLine(Convert.ToBoolean(0.3));
</pre>

<p>
We convert a <code>double</code> value to a <code>bool</code> value.
</p>

<pre class="explanation">
Console.WriteLine(Convert.ToInt32("452"));
</pre>

<p>
And here we convert a <code>string</code> to <code>int</code>.
</p>

<hr class="btm">

<pre class="code">
using System;

class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(Int32.Parse("34"));
        Console.WriteLine(Int32.Parse("-34"));
        Console.WriteLine(Int32.Parse("+34"));
    }
}
</pre>

<p>
Converting strings to integers is a very common task. Often when
we bring values from databases or GUI widgets. 
</p>


<pre class="explanation">
Console.WriteLine(Int32.Parse("34"));
</pre>

<p>
We use the <code>Parse()</code> method of the <code>Int32</code> class
to convert a <code>string</code> to <code>int</code> value. 
</p>


<p>
In this part of the C# tutorial, we covered data types and
their conversions.  
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 31, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

